package priv.mill.nio;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

import org.junit.Test;

public class SimpleSocket {

	public static void main(String[] args) throws Exception {
		ServerSocketChannel open = ServerSocketChannel.open();
		open.bind(new InetSocketAddress(9999));
		SocketChannel accept = open.accept();
		ByteBuffer allocate = ByteBuffer.allocate(1024);
		while(accept.read(allocate)>0) {
			allocate.flip();
			System.out.println(new String(allocate.array(),0,allocate.limit()));
			allocate.clear();
		}
		accept.shutdownInput();
		ByteBuffer wrap = ByteBuffer.wrap("客户端器您好！".getBytes());
		accept.write(wrap);
		
	}
	
	@Test
	public void client() throws Exception {
		SocketChannel open = SocketChannel.open(new InetSocketAddress(InetAddress.getLocalHost(), 9999));
		ByteBuffer wrap = ByteBuffer.wrap("服务器您好！".getBytes());
		open.write(wrap);
		wrap.clear();
		while(open.read(wrap)!=-1) {
			wrap.flip();
			System.out.println(new String(wrap.array(),0,wrap.limit()));
			wrap.clear();
		}
		
	}
	

}
